<template>
  <div class="roles">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb> 

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleBtn">添加角色</el-button>
        </el-col>
      </el-row>
      
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe style="width: 100%">
        <!-- 展开列区域 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row v-for="(item, index) in scope.row.children" :key="item.id" :class="['bdbottom', index === 0 ? 'bdtop' : '']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二、三级权限 -->
              <el-col :span="19">
                <el-row v-for="(citem, index) in item.children" :key="citem.id" :class="[index === 0 ? '' : 'bdtop']">
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightById(scope.row, citem.id)">{{citem.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable v-for="ccitem in citem.children" :key="ccitem.children"
                     type="warning" style="margin: 5px" @close="removeRightById(scope.row, ccitem.id)">
                     {{ccitem.authName}}
                  </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列区域 -->
        <el-table-column type="index"></el-table-column>
        <!-- 名称区域 -->
        <el-table-column prop="roleName" label="角色名称" width="300"></el-table-column>
        <!-- 描述区域 -->
        <el-table-column prop="roleDesc" label="角色描述"  width="300"></el-table-column>
        <!-- 操作区域 -->
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" @click="showEditRole(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleDialogClosed">
      <!-- 内容主题区域 -->
      <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="90px">
        <el-form-item label="角色" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAddRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="editRoleDialogClosed">
      <!-- 内容主题区域 -->
      <el-form :model="editRoleForm" :rules="editRoleFormRules" ref="editRoleFormRef" label-width="90px">
        <el-form-item label="角色" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureEditRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed">
      <!-- 树形控件区域 -->
      <el-tree
        :data="allRightList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        :props="treeProps"
        ref="treeRef">
      </el-tree>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureSetRight()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {  getRolesList, addRole, showEditRole, editRole, sureDeleteRole, deleteRoleRight,
          getRightsList, allotRight } from 'network/power'

export default {
  name: "Roles",
  data() {
    return {
      rolesList: [],

      // 角色ID
      roleId: 0,

      // 添加角色数据
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },

      // 修改角色数据
      editRoleForm: {

      },

      // 所有权限列表数据
      allRightList: [],

      // 默认勾选权限
      defKeys: [],

      // 分配权限数据
      setRightForm: {

      },

      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },

      // 添加角色对话框显示和隐藏
      addRoleDialogVisible: false,

      // 修改角色对话框显示和隐藏
      editRoleDialogVisible: false,

      // 分配权限对话框显示和隐藏
      setRightDialogVisible: false,

      // 添加角色表单规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 3, max: 10, message: '角色名的长度在3~10个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 4, max: 20, message: '角色描述的长度在4~20个字符', trigger: 'blur' }
        ]
      },
      
      // 修改角色表单规则
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 3, max: 10, message: '角色名的长度在3~10个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 4, max: 20, message: '角色描述的长度在4~20个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 发起获取角色列表请求
    getRolesList() {
      getRolesList().then(res => {
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.rolesList = res.data
        // console.log(this.rolesList);
      }).catch(err => {
        this.$message.error(err)
      })
    },

    // 点击 添加角色 按钮
    addRoleBtn() {
      this.addRoleDialogVisible = true
    },

    // 监听添加对话框关闭事件
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },

    // 监听修改对话框关闭事件
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },

    // 监听分配权限对话框关闭事件
    setRightDialogClosed() {
        this.defKeys = []
    },

    // 确认 添加角色
    sureAddRoles() {
      this.$refs.addRoleFormRef.validate(validate => {
        if(!validate) return
        addRole(this.addRoleForm).then(res => {
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
        }).catch(err => {
          this.$message.error(err)
        })
        // 关闭 添加角色对话框
        this.addRoleDialogVisible = false
        // 重新刷新 角色列表
        this.getRolesList()
      })
      
    },

    // 点击 编辑角色 按钮
    showEditRole(id) {
      showEditRole(id).then(res => {
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.editRoleForm = res.data
        this.editRoleDialogVisible = true
      }).catch(err => {
        this.$message.error(err)
      })
    },

    // 确认 修改角色
    sureEditRoles() {
      this.$refs.editRoleFormRef.validate(validate => {
        if(!validate) return
        editRole(this.editRoleForm).then(res => {
          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('修改成功')
          // 重新刷新 角色列表
          this.getRolesList()
        }).catch(err => {
          this.$message.error(err)
        })
        // 关闭 添加角色对话框
        this.editRoleDialogVisible = false
        
      })
    },

    // 点击删除 角色
    deleteRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sureDeleteRole(id).then(res => {
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.getRolesList()
          }).catch(err => {
            this.$message.error(err)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
    },

    // 根据id删除三级权限
    removeRightById(role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteRoleRight(role.id, rightId).then(res => {
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            role.children = res.data
          })
        }).catch(err => {
          this.$message.error(err)      
        })
    },

    // 展示分配权限的对话框
    showSetRightDialog(row) {
      this.roleId = row.id
      // 获取所有权限的数据
      getRightsList('tree').then(res => {
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.allRightList = res.data

        // 递归获取三级节点的id
        this.getLeafKeys(row, this.defKeys)

        // console.log(this.allRightList);
      }).catch(err => {
        this.$message.error(err)
      })
      this.setRightDialogVisible = true
    },

    // 确认分配选择权限
    sureSetRight() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(),
                   ...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keys);
      const arr = keys.join(',')
      console.log(arr);
      allotRight(this.roleId, { rids: arr }).then(res => {
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRolesList()
      }).catch(err => {
        this.$message.error(err)
      })
      this.setRightDialogVisible = false
    },

    // 通过递归形式，获取角色下所有三级权限的id，并保存到defKeys 数组中
    getLeafKeys(node, arr) {
      if(!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      });

    }
  }
}
</script>

<style>
  .el-breadcrumb,
  .el-row {
    padding: 20px 0;
    display: flex;
    align-items: center;
    
  }



  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }
</style>